/* EasyWay Game Engine
 * Copyright (C) 2007 Daniele Paggi.
 *  
 * Written by: 2007 Daniele Paggi<dshnt@hotmail.com>
 *   
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.easyway.editor.forms;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;

import org.easyway.debug.DebugManager;
import org.easyway.editor.analyzer.Analyzer;
import org.easyway.editor.commands.Command;
import org.easyway.editor.forms.southPanel.SouthOptionPanel;
import org.easyway.system.Core;
import org.easyway.system.StaticRef;

public class UEditor extends JFrame {

	private static final long serialVersionUID = 9010713958509042880L;

	public static EditorCore core;

	private static final int version = 2;

	private JPanel jContentPane = null;

	private JMenuBar jJMenuBar = null;

	private JMenuItem jMenuItem = null;

	private JMenu jMenu = null;

	private JToolBar toolBar = null;

	private static JPanel southPanel = null;

	// public static JPanel centerPanel = null;

	private static JPanel rightPanel = null;

	public static JPanel leftPanel = null;

	private JMenuItem saveButtonMenu = null;

	private JMenuItem loadButtonMenu = null;

	private JMenuItem playButtonMenu = null;

	private JMenuItem resetLeftPanel = null;

	// private JMenuItem addNewCoreMenu = null;

	private static JTextArea outputArea = null;

	private static JScrollPane scrollerOutArea = null;

	private static Navigator navigator = null;

	protected static Component hiddenSouthPanel = new SouthOptionPanel();

	protected static Component currentSouthPanel;

	/**
	 * indicates the state of the left-menu<br>
	 * the state is updated when all the object from the left-panel are removed
	 */
	static int menuState = 0;

	/**
	 * This is the default constructor
	 */
	public UEditor() {
		super();
		initialize();
		setVisible(true);
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(1024, 768);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setResizable(true);
		this.setPreferredSize(new Dimension(1024, 768));
		this.setMinimumSize(new Dimension(1024, 768));
		this.setJMenuBar(getJJMenuBar());
		this.setContentPane(getJContentPane());
		this.setTitle("UEditor version: " + version);
		final PrintStream defout = System.out;

		// initialize output Area
		PrintStream p = new PrintStream(new OutputStream() {
			String temp = "";

			public void write(int b) {
				temp += (char) b;
				if (b == '\n' || temp.length() >= 10) {
					outputArea.append(temp);
					outputArea.setCaretPosition(outputArea.getText().length());
					temp = "";
				}
				// System.setOut(defout);
				defout.append((char) b);
			}
		});
		System.setErr(p);
		System.setOut(p);
		addCore();
		// Analyzer.getClasses();
		Analyzer.searchUEditor();
		Analyzer.addUEditorClasses();
		System.out.println("UEditor version: " + version
				+ "\nEditor Initilized");
		this.setVisible(true);
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.setPreferredSize(new Dimension(1024, 768));
			jContentPane.add(getToolBar(), BorderLayout.NORTH);
			jContentPane.add(getSouthPanel(), BorderLayout.SOUTH);
			jContentPane.add(getDesktop()/* getCenterPanel() */,
				BorderLayout.CENTER);
			jContentPane.add(getRightPanel(), BorderLayout.EAST);
			jContentPane.add(getLeftPanel(), BorderLayout.WEST);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jJMenuBar
	 * 
	 * @return javax.swing.JMenuBar
	 */
	private JMenuBar getJJMenuBar() {
		if (jJMenuBar == null) {
			jJMenuBar = new JMenuBar();
			jJMenuBar.add(getJMenu());
		}
		return jJMenuBar;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getJMenuItem() {
		if (jMenuItem == null) {
			jMenuItem = new JMenuItem();
			jMenuItem.setText("New");
		}
		return jMenuItem;
	}

	/**
	 * This method initializes jMenu
	 * 
	 * @return javax.swing.JMenu
	 */
	private JMenu getJMenu() {
		if (jMenu == null) {
			jMenu = new JMenu();
			jMenu.setText("File");
			jMenu.add(getJMenuItem());
		}
		return jMenu;
	}

	/**
	 * This method initializes toolBar
	 * 
	 * @return javax.swing.JToolBar
	 */
	private JToolBar getToolBar() {
		if (toolBar == null) {
			toolBar = new JToolBar();
			toolBar.setFloatable(false);
			toolBar.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
			toolBar.setPreferredSize(new Dimension(101, 33));
			toolBar.add(getResetLeftPanel());
			toolBar.add(getPlayButtonMenu());
			toolBar.add(getLoadButtonMenu());
			toolBar.add(getSaveButtonMenu());
			// toolBar.add(getAddNewCoreMenu());
		}
		return toolBar;
	}

	/**
	 * This method initializes saveButtonMenu
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getSaveButtonMenu() {
		if (saveButtonMenu == null) {
			saveButtonMenu = new JMenuItem();
			saveButtonMenu.setIcon(new ImageIcon(getClass().getResource(
				"/org/easyway/editor/forms/images/file.save.gif")));
			saveButtonMenu.setSize(new Dimension(29, 29));
			saveButtonMenu.setText("save");
			saveButtonMenu.setPreferredSize(new Dimension(0, 29));
			saveButtonMenu.setToolTipText("");
			saveButtonMenu
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent e) {
						Analyzer.removeFromLPanel();
						try {
							Analyzer.addStaticMethod(
								Core.class.getMethod("save",
									new Class[] { String.class })).command();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				});
		}
		return saveButtonMenu;
	}

	/**
	 * This method initializes southPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	private static JPanel getSouthPanel() {
		if (southPanel == null) {
			southPanel = new JPanel();
			southPanel.setPreferredSize(new Dimension(1024, 85));
			southPanel.setLayout(new BorderLayout());
			southPanel.add(getScrollerOutArea(), BorderLayout.CENTER);
			southPanel.add(getNavigator(), BorderLayout.EAST);
		}
		return southPanel;
	}

	// /**
	// * This method initializes centerPanel
	// *
	// * @return javax.swing.JPanel
	// */
	// public static JPanel getCenterPanel() {
	// if (centerPanel == null) {
	// centerPanel = new JPanel();
	//
	// centerPanel.setLayout(new BorderLayout());
	// centerPanel.setPreferredSize(new Dimension(800, 600));
	// centerPanel.setSize(800, 600);
	// centerPanel.add(getDesktop(), BorderLayout.CENTER);
	// }
	// return centerPanel;
	// }

	/**
	 * This method initializes rightPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getRightPanel() {
		if (rightPanel == null) {
			rightPanel = new JPanel();
			rightPanel.setLayout(new GridBagLayout());
		}
		return rightPanel;
	}

	/**
	 * This method initializes leftPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	public static JPanel getLeftPanel() {
		if (leftPanel == null) {
			GridLayout gridLayout = new GridLayout();
			gridLayout.setRows(20);
			gridLayout.setVgap(0);
			gridLayout.setColumns(1);
			leftPanel = new JPanel() {
				private static final long serialVersionUID = -3452508431106460577L;

				public void removeAll() {
					super.removeAll();
					menuState++;
				}
			};
			leftPanel.setLayout(gridLayout);
			leftPanel.setPreferredSize(new Dimension(224, 600));
		}
		return leftPanel;
	}

	/**
	 * This method initializes loadButtonMenu
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getLoadButtonMenu() {
		if (loadButtonMenu == null) {
			loadButtonMenu = new JMenuItem();
			loadButtonMenu.setToolTipText("load");
			loadButtonMenu.setText("open");
			loadButtonMenu.setPreferredSize(new Dimension(100, 29));
			loadButtonMenu.setIcon(new ImageIcon(getClass().getResource(
				"/org/easyway/editor/forms/images/file.open.png")));
			loadButtonMenu
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent e) {
						Analyzer.removeFromLPanel();
						try {
							Analyzer.addStaticMethod(
								Core.class.getMethod("load",
									new Class[] { String.class })).command();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				});
		}
		return loadButtonMenu;
	}

	private static JDesktopPane desktop = null;

	private float EdCamx, EdCamy;

	/**
	 * This method initializes playButtonMenu
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getPlayButtonMenu() {
		if (playButtonMenu == null) {
			playButtonMenu = new JMenuItem();
			playButtonMenu.setText("start game");
			playButtonMenu.setPreferredSize(new Dimension(0, 35));
			playButtonMenu.setIcon(new ImageIcon(getClass().getResource(
				"/org/easyway/editor/forms/images/play.GIF")));
			playButtonMenu
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent e) {
						if (!DebugManager.debug) {
							DebugManager.debug = true;
							// debugging mode on
							playButtonMenu.setText("start game");
							int n = JOptionPane.showConfirmDialog(UEditor
								.getDesktop(),
								"do you want restore the game state?",
								"Restore the game state",
								JOptionPane.YES_NO_OPTION);
							if (n == 0) {
								new Command() {

									public void creation() {
										Core.load("gameState.state");
										StaticRef.getCamera().setx(EdCamx);
										StaticRef.getCamera().sety(EdCamy);
										destroy();
									}

									public void loop() {
										// TODO Auto-generated method stub

									}

									public void render() {
										// TODO Auto-generated method stub

									}

								};

							}
						} else { // DebugManager.debug == true
							int n = JOptionPane.showConfirmDialog(UEditor
								.getDesktop(),
								"do you want save the game state?",
								"Save the game state",
								JOptionPane.YES_NO_OPTION);
							if (n == 0) {
								new Command() {

									public void creation() {
										Core.save("gameState.state");
										destroy();
										DebugManager.debug = false;
									}

									public void loop() {
										// TODO Auto-generated method stub

									}

									public void render() {
										// TODO Auto-generated method stub

									}

								};
							} else {
								DebugManager.debug = false;
							}
							EdCamx = StaticRef.getCamera().getx();
							EdCamy = StaticRef.getCamera().gety();
							playButtonMenu.setText("pause game");

						}
					}
				});
		}
		return playButtonMenu;
	}

	/**
	 * This method initializes outputArea
	 * 
	 * @return javax.swing.JTextArea
	 */
	private static JTextArea getOutputArea() {
		if (outputArea == null) {
			outputArea = new JTextArea();
			// outputArea.setPreferredSize(new Dimension(5, 30));
			outputArea.setEditable(false);
		}
		return outputArea;
	}

	@Override protected void finalize() throws Throwable {
		super.finalize();
		if (!core.isDestroyed())
			core.destroy();
	}

	/**
	 * This method initializes scrollerOutArea
	 * 
	 * @return javax.swing.JScrollPane
	 */
	private static JScrollPane getScrollerOutArea() {
		if (scrollerOutArea == null) {
			scrollerOutArea = new JScrollPane(getOutputArea());
			scrollerOutArea.setName("scrollerOutArea");
			scrollerOutArea.setViewportView(getOutputArea());
			currentSouthPanel = scrollerOutArea;
		}
		return scrollerOutArea;
	}

	/**
	 * This method initializes navigator
	 * 
	 * @return org.easyway.editor.forms.Navigator
	 */
	public static Navigator getNavigator() {
		if (navigator == null) {
			navigator = new Navigator();
			navigator.setName("navigator");
			navigator.setPreferredSize(new Dimension(85, 85));
		}
		return navigator;
	}

	/**
	 * This method initializes resetLeftPanel
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getResetLeftPanel() {
		if (resetLeftPanel == null) {
			resetLeftPanel = new JMenuItem();
			resetLeftPanel.setText("Show UEditor objects");
			resetLeftPanel.setPreferredSize(new Dimension(10, 29));
			resetLeftPanel.setIcon(new ImageIcon(getClass().getResource(
				"/org/easyway/editor/forms/images/description.gif")));
			resetLeftPanel
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent e) {
						getLeftPanel().removeAll();
						Analyzer.addUEditorClasses();
						getLeftPanel().repaint();
					}
				});
		}
		return resetLeftPanel;
	}

	/**
	 * This method initializes addNewCoreMenu
	 * 
	 * @return javax.swing.JMenuItem
	 */
	// private JMenuItem getAddNewCoreMenu() {
	// if (addNewCoreMenu == null) {
	// addNewCoreMenu = new JMenuItem();
	// addNewCoreMenu.setText("New Core");
	// addNewCoreMenu.setPreferredSize(new Dimension(10, 29));
	// addNewCoreMenu.setIcon(new ImageIcon(getClass().getResource(
	// "/org/easyway/editor/forms/images/description.gif")));
	// addNewCoreMenu
	// .addActionListener(new java.awt.event.ActionListener() {
	// public void actionPerformed(java.awt.event.ActionEvent e) {
	// addCore();
	// }
	// });
	// }
	// return addNewCoreMenu;
	// }
	/**
	 * switchs the south components
	 */
	public static void switchSouthComp() {
		if (hiddenSouthPanel == null || currentSouthPanel == null) {
			new Exception("hidedSouthPanel or currentSouthPanel null")
				.printStackTrace();
			return;
		}
		Component swap = hiddenSouthPanel;
		hiddenSouthPanel = currentSouthPanel;
		currentSouthPanel = swap;

		getSouthPanel().remove(hiddenSouthPanel);
		getSouthPanel().add(currentSouthPanel);
		getSouthPanel().validate();
		getSouthPanel().repaint();
		hiddenSouthPanel.setVisible(false);
		currentSouthPanel.setVisible(true);

	}

	/**
	 * This method initializes desktop
	 * 
	 * @return javax.swing.JDesktopPane
	 */
	private static JDesktopPane getDesktop() {
		if (desktop == null) {
			desktop = new JDesktopPane();
			desktop.setBackground(Color.GRAY);
			// core = new EditorCore(800, 600, desktop);
		}
		return desktop;
	}

	static WindowCore Wcore;

	public static void addCore() {
		Wcore = new WindowCore();
		Wcore.setVisible(true);
		getDesktop().add(Wcore);
		Wcore.maximize();
		Wcore.addGeCore();
	}

} // @jve:decl-index=0:visual-constraint="10,10"
